package com.example.industry.dao.impl;

import com.example.industry.dao.UserDao;
import com.example.industry.util.MySqlConnector;
import com.example.industry.dao.ProjectDao;
import com.example.industry.entity.Project;
import com.example.industry.enums.Roles;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

@Repository
public class ProjectDaoImpl implements ProjectDao {
    @Resource
    UserDao userDao;
    @Override
    public Project findById(Integer id) {
        Project project = new Project();
        MySqlConnector connector = new MySqlConnector();
        try {
            connector.connectDatabase();
            Connection conn = connector.getConnection();
            String sql = "select * from project where project_id = " + id;
            try (Statement stmt = conn.createStatement()) {
                ResultSet resultSet = stmt.executeQuery(sql);
                if (resultSet.next()) {
                    project.setProjectId(resultSet.getInt("project_id"));
                    project.setProjectName(resultSet.getString("project_name"));
                    project.setProjectIntroduction(resultSet.getString("project_introduction"));
                } else return null;
                // 获取项目经理id
                String sql2 = "select * from user_project where project_id = " + id + " and role = 0";
                ResultSet resultSet1 = stmt.executeQuery(sql2);
                if (resultSet1.next()){
                    project.setChairmanId(resultSet1.getInt("user_id"));
                } else return null;
            }
            connector.closeConnection();
            return project;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    @Override
    public Boolean deleteById(Integer id) {
        if (findById(id) == null) return Boolean.FALSE;
        MySqlConnector connector = new MySqlConnector();
        try
        {
            connector.connectDatabase();
            Connection conn = connector.getConnection();
            try (Statement stmt = conn.createStatement())
            {
                // 先查询出一个项目对应的任务的id列表，先把列表id 的task全部删除，然后再删除项目（级联删除）即可

                String sql1 = "select * from project_task where project_id = " + id;
                String sq2 = "delete from task where task_id = " ;
                ResultSet resultSet = stmt.executeQuery(sql1);
                while (resultSet.next()){
                    int result1 = stmt.executeUpdate(sq2 + resultSet.getInt("task_id"));
                    if (result1 <= 0)return Boolean.FALSE;
                }
                String sql = "delete from project where project_id = " + id;
                int result = stmt.executeUpdate(sql);
                if (result <= 0) return Boolean.FALSE;
            }
            connector.closeConnection();
            return Boolean.TRUE;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return Boolean.FALSE;
        }
    }
    @Override
    public Boolean update(Project project) {
        if (project == null || project.getProjectName() == null || project.getChairmanId() == null
        || project.getProjectIntroduction() == null) return Boolean.FALSE;
        MySqlConnector connector = new MySqlConnector();
        try
        {
            connector.connectDatabase();
            Connection conn = connector.getConnection();

            try (Statement stmt = conn.createStatement())
            {
                String sql = "update project set project_name = '" + project.getProjectName() +
                    "',project_introduction = '" + project.getProjectIntroduction() +
                    "' where project_id = " + project.getProjectId();
                System.out.println(sql);
                if (stmt.executeUpdate(sql) <= 0) return Boolean.FALSE;
            }
            connector.closeConnection();
            return Boolean.TRUE;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return Boolean.FALSE;
        }
    }
    @Override
    public Boolean addProject(Project project) {
        if (project == null || project.getProjectName() == null || project.getChairmanId() == null || project.getProjectIntroduction() == null) return Boolean.FALSE;
        MySqlConnector connector = new MySqlConnector();
        int tempProjectId;
        try
        {
            connector.connectDatabase();
            Connection conn = connector.getConnection();

            try (Statement stmt = conn.createStatement())
            {
                String sql = "insert into project "+"(project_name,project_introduction)" +
                    "values( '" + project.getProjectName() + "','" +
                    project.getProjectIntroduction() + "')";
                if (stmt.executeUpdate(sql,Statement.RETURN_GENERATED_KEYS) <= 0) return Boolean.FALSE;
                ResultSet generatedKeys = stmt.getGeneratedKeys();
                if (generatedKeys != null) {
                    generatedKeys.next();
                    tempProjectId = generatedKeys.getInt(1);
                } else return Boolean.FALSE;
                String sql1 = "insert into user_project (user_id,project_id,role)" +
                        "values (" + project.getChairmanId() + "," + tempProjectId +","+ 0 + ")";
                if (stmt.executeUpdate(sql1) <= 0) return Boolean.FALSE;
            }
            connector.closeConnection();
            return Boolean.TRUE;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return Boolean.FALSE;
        }
    }
    @Override
    public Boolean addMember(Integer projectId, Integer userId, Roles role) {
        if (projectId == null  || userId == null || role == null) return Boolean.FALSE;
        int limit = 0;
        switch (role){
            case ADMIN -> limit = 1;
            case COMMON -> limit = 2;
        }
        MySqlConnector connector = new MySqlConnector();
        try
        {
            connector.connectDatabase();
            Connection conn = connector.getConnection();
            String sql = "insert into user_project "+"(project_id,user_id,role)" +
                    "values( " + projectId + "," + userId + "," + limit + ")";
            try (Statement stmt = conn.createStatement())
            {
                int result = stmt.executeUpdate(sql);
                if (result <= 0) return Boolean.FALSE;
            }
            connector.closeConnection();
            return Boolean.TRUE;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return Boolean.FALSE;
        }
    }
    @Override
    public Boolean deleteMember(Integer projectId, Integer userId) {
        if (projectId == null  || userId == null) return Boolean.FALSE;
        MySqlConnector connector = new MySqlConnector();
        try
        {
            connector.connectDatabase();
            Connection conn = connector.getConnection();
            String sql = "DELETE from user_project "+ " where project_id = " + projectId + " and user_id = " + userId;
            try (Statement stmt = conn.createStatement())
            {
                int result = stmt.executeUpdate(sql);
                if (result <= 0) return Boolean.FALSE;
            }
            connector.closeConnection();
            return Boolean.TRUE;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return Boolean.FALSE;
        }
    }
    @Override
    public List<Integer> findMembersByProjectId(Integer projectId,Roles role) {
        List<Integer> result = new ArrayList<>();
        MySqlConnector connector = new MySqlConnector();
        try {
            connector.connectDatabase();
            Connection conn = connector.getConnection();
            String sql;
            int limit = 0;
            switch (role){
                case ADMIN -> limit = 1;
                case COMMON -> limit = 2;
                case OWNER -> limit = 0;
                case ALL -> limit = 3;
            }
            if (limit == 3) sql = "select * from user_project where project_id = "+ projectId;
            else sql = "select * from user_project where project_id = " + projectId + " and role = " + limit;
            try (Statement stmt = conn.createStatement()) {
                ResultSet resultSet = stmt.executeQuery(sql);

                while (resultSet.next())
                {
                    result.add(Integer.valueOf(resultSet.getString("user_id")));
                }
                connector.closeConnection();
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
    }
    @Override
    public boolean updateUserRoleInProject(Integer projectId, Integer userId, Roles role) {
        if(findById(projectId) == null || userDao.findById(userId) == null) return false;
        MySqlConnector connector = new MySqlConnector();
        try
        {
            connector.connectDatabase();
            Connection conn = connector.getConnection();

            try (Statement stmt = conn.createStatement())
            {
                int limit = 0;
                switch (role){
                    case ADMIN -> limit = 1;
                    case COMMON -> limit = 2;
                }
                String sql = "update user_project set role = " + limit +
                        " where project_id = " + projectId + " and user_id = " + userId;
                if (stmt.executeUpdate(sql) <= 0) return Boolean.FALSE;
            }
            connector.closeConnection();
            return Boolean.TRUE;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return Boolean.FALSE;
        }
    }


}
